import React, { useState, useEffect, useCallback } from "react";
import {
  Card,
  Radio,
  Checkbox,
  Input,
  Button,
  Progress,
  Space,
  Alert,
  Modal,
  message,
  Typography,
  Affix,
  Row,
  Col,
  Tag,
  Tooltip,
  List,
  Divider,
  Statistic,
  Popconfirm,
  Spin,
} from "antd";
import {
  ClockCircleOutlined,
  ExclamationCircleOutlined,
  SaveOutlined,
  SendOutlined,
  QuestionCircleOutlined,
  CheckOutlined,
  CloseOutlined,
  WarningOutlined,
  InfoCircleOutlined,
  FileTextOutlined,
  BookOutlined,
} from "@ant-design/icons";
import { useParams, useNavigate } from "react-router-dom";
import { useUser } from "../../../contexts/UserContext";
import { useExamContext } from "../../../contexts/ExamContext";
import "./styles.scss";

const { TextArea } = Input;
const { Title, Text, Paragraph } = Typography;
const { confirm } = Modal;

interface Question {
  id: string;
  type: "single" | "multiple" | "essay" | "judge" | "fill";
  question: string;
  options?: string[];
  answer?: string | string[];
  score: number;
  section: string;
  knowledgePoint?: string;
}

interface ExamInfo {
  id: string;
  title: string;
  description: string;
  totalScore: number;
  duration: number; // 分钟
  questions: Question[];
  rules: string[];
  course: string;
  knowledgePoints: string[];
}

const ExamTaking: React.FC = () => {
  const { examId } = useParams();
  const navigate = useNavigate();
  const { user } = useUser();
  const { 
    getExamById, 
    submitExam: contextSubmitExam, 
    saveAndExit: contextSaveAndExit,
    startExam: contextStartExam 
  } = useExamContext();

  const [examInfo, setExamInfo] = useState<ExamInfo | null>(null);
  const [answers, setAnswers] = useState<Record<string, any>>({});
  const [timeLeft, setTimeLeft] = useState(7200); // 2小时考试时间（秒）
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [autoSaving, setAutoSaving] = useState(false);
  const [lastSaveTime, setLastSaveTime] = useState<Date | null>(null);
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [loading, setLoading] = useState(true);
  const [examStarted, setExamStarted] = useState(false);
  const [showExitConfirm, setShowExitConfirm] = useState(false);
  const [startTime, setStartTime] = useState<Date | null>(null);

  // 根据考试ID生成不同的试题
  const generateExamQuestions = (examId: string): Question[] => {
    const questionTemplates = {
      "1": { // 数据结构期中考试
        course: "数据结构与算法",
        knowledgePoints: ["线性表", "栈和队列", "树结构", "图算法", "排序算法"],
        questions: [
          {
            id: "1",
            type: "single" as const,
            section: "线性表",
            knowledgePoint: "线性表",
            question: "下列关于线性表的描述，正确的是？",
            options: [
              "线性表中的元素可以是不同类型的数据",
              "线性表只能顺序存储，不能链式存储",
              "线性表中的元素具有唯一的前驱和后继",
              "线性表是一种非线性数据结构"
            ],
            score: 5,
          },
          {
            id: "2",
            type: "single" as const,
            section: "栈和队列",
            knowledgePoint: "栈和队列",
            question: "栈的特点是？",
            options: [
              "先进先出（FIFO）",
              "后进先出（LIFO）",
              "随机存取",
              "双向存取"
            ],
            score: 5,
          },
          {
            id: "3",
            type: "fill" as const,
            section: "树结构",
            knowledgePoint: "树结构",
            question: "二叉树中，度为2的节点称为____节点。",
            score: 3,
          },
          {
            id: "4",
            type: "essay" as const,
            section: "图算法",
            knowledgePoint: "图算法",
            question: "请简述深度优先搜索（DFS）和广度优先搜索（BFS）的区别，并说明它们各自的应用场景。",
            score: 15,
          },
          {
            id: "5",
            type: "multiple" as const,
            section: "排序算法",
            knowledgePoint: "排序算法",
            question: "以下哪些排序算法的时间复杂度为O(nlogn)？",
            options: [
              "快速排序",
              "归并排序",
              "堆排序",
              "冒泡排序"
            ],
            score: 8,
          }
        ]
      },
      "2": { // 数据库系统期末考试
        course: "数据库系统原理",
        knowledgePoints: ["关系数据库", "SQL语言", "数据库设计", "事务管理", "查询优化"],
        questions: [
          {
            id: "1",
            type: "single" as const,
            section: "关系数据库",
            knowledgePoint: "关系数据库",
            question: "关系数据库的三大范式不包括？",
            options: [
              "第一范式（1NF）",
              "第二范式（2NF）",
              "第三范式（3NF）",
              "第四范式（4NF）"
            ],
            score: 5,
          },
          {
            id: "2",
            type: "fill" as const,
            section: "SQL语言",
            knowledgePoint: "SQL语言",
            question: "SQL中用于查询数据的关键字是____。",
            score: 3,
          },
          {
            id: "3",
            type: "essay" as const,
            section: "数据库设计",
            knowledgePoint: "数据库设计",
            question: "请说明数据库设计中的概念设计、逻辑设计和物理设计的主要内容。",
            score: 15,
          },
          {
            id: "4",
            type: "judge" as const,
            section: "事务管理",
            knowledgePoint: "事务管理",
            question: "事务的ACID特性中，A代表原子性（Atomicity）。",
            score: 5,
          },
          {
            id: "5",
            type: "multiple" as const,
            section: "查询优化",
            knowledgePoint: "查询优化",
            question: "以下哪些是查询优化的常用技术？",
            options: [
              "索引优化",
              "查询重写",
              "统计信息",
              "并行处理"
            ],
            score: 8,
          }
        ]
      },
      "3": { // 计算机网络实验考核
        course: "计算机网络",
        knowledgePoints: ["网络协议", "网络配置", "网络编程", "协议分析"],
        questions: [
          {
            id: "1",
            type: "single" as const,
            section: "网络协议",
            knowledgePoint: "网络协议",
            question: "TCP协议属于OSI七层模型中的哪一层？",
            options: [
              "物理层",
              "数据链路层",
              "网络层",
              "传输层"
            ],
            score: 5,
          },
          {
            id: "2",
            type: "fill" as const,
            section: "网络配置",
            knowledgePoint: "网络配置",
            question: "IPv4地址由____位二进制数组成。",
            score: 3,
          },
          {
            id: "3",
            type: "essay" as const,
            section: "网络编程",
            knowledgePoint: "网络编程",
            question: "请编写一个简单的TCP客户端程序，实现与服务器的连接和数据传输。",
            score: 20,
          },
          {
            id: "4",
            type: "judge" as const,
            section: "协议分析",
            knowledgePoint: "协议分析",
            question: "HTTP协议是无状态协议。",
            score: 5,
          }
        ]
      }
    };

    const template = questionTemplates[examId as keyof typeof questionTemplates];
    if (!template) {
      // 默认模板
      return [
        {
          id: "1",
          type: "single" as const,
          section: "基础知识",
          question: "这是一道默认的选择题？",
          options: ["选项A", "选项B", "选项C", "选项D"],
          score: 5,
        }
      ];
    }

    return template.questions;
  };

  // 模拟考试信息
  const mockExamInfo: ExamInfo = {
    id: examId || "1",
    title: examId === "1" ? "数据结构期中考试" : 
           examId === "2" ? "数据库系统期末考试" : 
           examId === "3" ? "计算机网络实验考核" : "默认考试",
    description: examId === "1" ? "本次考试涵盖线性表、栈、队列、树、图等基础数据结构，以及相关算法的实现和应用。" :
                 examId === "2" ? "期末考试将全面考察数据库系统的基本概念、SQL语言、数据库设计和优化等内容。" :
                 examId === "3" ? "上机实验考核，包括网络配置、协议分析、网络编程等实践内容。" :
                 "默认考试描述",
    totalScore: 100,
    duration: 120,
    course: examId === "1" ? "数据结构与算法" : 
            examId === "2" ? "数据库系统原理" : 
            examId === "3" ? "计算机网络" : "默认课程",
    knowledgePoints: examId === "1" ? ["线性表", "栈和队列", "树结构", "图算法", "排序算法"] :
                     examId === "2" ? ["关系数据库", "SQL语言", "数据库设计", "事务管理", "查询优化"] :
                     examId === "3" ? ["网络协议", "网络配置", "网络编程", "协议分析"] :
                     ["基础知识"],
    rules: [
      "考试时间为120分钟，请合理安排答题时间",
      "考试期间不得切换浏览器窗口或打开其他应用",
      "所有题目均为必答题，请仔细阅读题目要求",
      "考试结束前5分钟系统将自动保存并提交答案",
      "考试过程中系统会自动保存答案，请放心答题",
      "如需退出考试，请使用'保存并退出'功能",
    ],
    questions: generateExamQuestions(examId || "1"),
  };

  // 加载考试信息
  useEffect(() => {
    const loadExamInfo = async () => {
      try {
        setLoading(true);
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        setExamInfo(mockExamInfo);
        setTimeLeft(mockExamInfo.duration * 60);
        
        // 检查是否有保存的答案
        const savedAnswers = localStorage.getItem(`exam_${examId}_answers`);
        if (savedAnswers) {
          setAnswers(JSON.parse(savedAnswers));
        }
        
        // 检查考试是否已经开始
        const examStartTime = localStorage.getItem(`exam_${examId}_start_time`);
        if (examStartTime) {
          const startTime = new Date(examStartTime).getTime();
          const now = new Date().getTime();
          const elapsed = Math.floor((now - startTime) / 1000);
          const remaining = mockExamInfo.duration * 60 - elapsed;
          
          if (remaining > 0) {
            setTimeLeft(remaining);
            setExamStarted(true);
            setStartTime(new Date(examStartTime));
          } else {
            // 考试时间已到，自动提交
            message.warning("考试时间已到，系统将自动提交答案");
            handleSubmit(true);
          }
        }
      } catch (error) {
        message.error("加载考试信息失败");
        console.error("加载考试信息失败:", error);
      } finally {
        setLoading(false);
      }
    };

    loadExamInfo();
  }, [examId]);

  // 开始考试
  const startExam = () => {
    setExamStarted(true);
    const now = new Date();
    setStartTime(now);
    localStorage.setItem(`exam_${examId}_start_time`, now.toISOString());
    
    // 通知上下文开始考试
    if (examId) {
      contextStartExam(examId);
    }
    
    message.success("考试开始，计时器已启动");
  };

  // 自动保存
  useEffect(() => {
    if (!examStarted || !examInfo) return;

    const autoSave = () => {
      setAutoSaving(true);
      localStorage.setItem(`exam_${examId}_answers`, JSON.stringify(answers));
      setLastSaveTime(new Date());
      setAutoSaving(false);
    };

    const interval = setInterval(autoSave, 30000); // 每30秒自动保存
    return () => clearInterval(interval);
  }, [answers, examStarted, examId, examInfo]);

  // 倒计时
  useEffect(() => {
    if (!examStarted || timeLeft <= 0) return;

    const timer = setInterval(() => {
      setTimeLeft(prev => {
        if (prev <= 1) {
          // 时间到，自动提交
          message.warning("考试时间已到，系统将自动提交答案");
          handleSubmit(true);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [examStarted, timeLeft]);

  // 页面离开提示
  useEffect(() => {
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (examStarted && !isSubmitting) {
        e.preventDefault();
        e.returnValue = "考试正在进行中，离开页面将自动交卷。确定要离开吗？";
        return e.returnValue;
      }
    };

    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => window.removeEventListener("beforeunload", handleBeforeUnload);
  }, [examStarted, isSubmitting]);

  const handleAnswerChange = (questionId: string, value: any) => {
    setAnswers(prev => ({
      ...prev,
      [questionId]: value
    }));
  };

  // 保存并退出
  const handleSaveAndExit = () => {
    confirm({
      title: "保存并退出考试",
      content: (
        <div>
          <p>您确定要保存当前答案并退出考试吗？</p>
          <Alert
            message="重要提示"
            description="退出后考试仍在进行中，系统会继续计时。您可以稍后重新进入继续答题。"
            type="warning"
            showIcon
            style={{ marginTop: 12 }}
          />
        </div>
      ),
      okText: "保存并退出",
      cancelText: "继续考试",
      onOk: () => {
        // 保存答案
        localStorage.setItem(`exam_${examId}_answers`, JSON.stringify(answers));
        
        // 通知上下文保存并退出
        if (examId) {
          contextSaveAndExit(examId, answers);
        }
        
        message.success("答案已保存，您可以稍后继续考试");
        navigate("/student/exams");
      }
    });
  };

  // 提交考试
  const handleSubmit = (isAutoSubmit = false) => {
    if (!isAutoSubmit) {
      confirm({
        title: "确认提交考试",
        content: (
          <div>
            <p>您确定要提交考试吗？提交后将无法修改答案。</p>
            <Alert
              message="提交确认"
              description="请确认所有题目都已作答，提交后将进入已完成考试列表。"
              type="info"
              showIcon
              style={{ marginTop: 12 }}
            />
          </div>
        ),
        okText: "确认提交",
        cancelText: "继续答题",
        onOk: () => doSubmit(),
      });
    } else {
      doSubmit();
    }
  };

  const doSubmit = async () => {
    setIsSubmitting(true);
    try {
      // 保存答案
      localStorage.setItem(`exam_${examId}_answers`, JSON.stringify(answers));
      
      // 计算实际用时
      const timeSpent = startTime ? Math.floor((new Date().getTime() - startTime.getTime()) / 60000) : 0;
      
      // 通知上下文提交考试
      if (examId) {
        contextSubmitExam(examId, answers, timeSpent);
      }
      
      // 清除考试状态
      localStorage.removeItem(`exam_${examId}_start_time`);
      localStorage.removeItem(`exam_${examId}_answers`);
      
      // 模拟提交
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      message.success("考试提交成功！");
      
      // 跳转到已完成考试列表
      navigate("/student/exams");
    } catch (error) {
      message.error("提交失败，请重试");
    } finally {
      setIsSubmitting(false);
    }
  };

  const formatTime = (seconds: number) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = seconds % 60;
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  const getAnsweredCount = () => {
    return Object.keys(answers).length;
  };

  const getProgressPercent = () => {
    if (!examInfo) return 0;
    return Math.round((getAnsweredCount() / examInfo.questions.length) * 100);
  };

  const renderQuestion = (question: Question, index: number) => {
    const questionNumber = index + 1;
    const isAnswered = answers[question.id] !== undefined;

    return (
      <Card
        key={question.id}
        title={
          <Space>
            <Tag color={isAnswered ? "green" : "default"}>
              第{questionNumber}题
            </Tag>
            <Tag color="blue">{question.section}</Tag>
            {question.knowledgePoint && (
              <Tag color="purple">{question.knowledgePoint}</Tag>
            )}
            <Text type="secondary">({question.score}分)</Text>
          </Space>
        }
        style={{ marginBottom: 16 }}
        extra={
          <Space>
            {isAnswered && <CheckOutlined style={{ color: '#52c41a' }} />}
            <Text type="secondary">{question.type === 'single' ? '单选题' : 
                                   question.type === 'multiple' ? '多选题' :
                                   question.type === 'essay' ? '简答题' :
                                   question.type === 'judge' ? '判断题' : '填空题'}</Text>
          </Space>
        }
      >
        <div style={{ marginBottom: 16 }}>
          <Paragraph>{question.question}</Paragraph>
        </div>

        {question.type === "single" && question.options && (
          <Radio.Group
            value={answers[question.id]}
            onChange={(e) => handleAnswerChange(question.id, e.target.value)}
          >
            <Space direction="vertical">
              {question.options.map((option, optionIndex) => (
                <Radio key={optionIndex} value={String.fromCharCode(65 + optionIndex)}>
                  {String.fromCharCode(65 + optionIndex)}. {option}
                </Radio>
              ))}
            </Space>
          </Radio.Group>
        )}

        {question.type === "multiple" && question.options && (
          <Checkbox.Group
            value={answers[question.id] || []}
            onChange={(values) => handleAnswerChange(question.id, values)}
          >
            <Space direction="vertical">
              {question.options.map((option, optionIndex) => (
                <Checkbox key={optionIndex} value={String.fromCharCode(65 + optionIndex)}>
                  {String.fromCharCode(65 + optionIndex)}. {option}
                </Checkbox>
              ))}
            </Space>
          </Checkbox.Group>
        )}

        {question.type === "essay" && (
          <TextArea
            rows={6}
            placeholder="请在此输入您的答案..."
            value={answers[question.id] || ""}
            onChange={(e) => handleAnswerChange(question.id, e.target.value)}
          />
        )}

        {question.type === "judge" && (
          <Radio.Group
            value={answers[question.id]}
            onChange={(e) => handleAnswerChange(question.id, e.target.value)}
          >
            <Space>
              <Radio value={true}>正确</Radio>
              <Radio value={false}>错误</Radio>
            </Space>
          </Radio.Group>
        )}

        {question.type === "fill" && (
          <Input
            placeholder="请在此输入您的答案..."
            value={answers[question.id] || ""}
            onChange={(e) => handleAnswerChange(question.id, e.target.value)}
          />
        )}
      </Card>
    );
  };

  const renderQuestionNav = () => {
    if (!examInfo) return null;

    return (
      <Card title="题目导航" size="small">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8 }}>
          {examInfo.questions.map((question, index) => (
            <Button
              key={question.id}
              type={answers[question.id] !== undefined ? "primary" : "default"}
              size="small"
              onClick={() => setCurrentQuestion(index)}
              style={{
                backgroundColor: currentQuestion === index ? '#1890ff' : undefined,
                color: currentQuestion === index ? 'white' : undefined,
              }}
            >
              {index + 1}
            </Button>
          ))}
        </div>
      </Card>
    );
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
        <div style={{ marginTop: 16 }}>正在加载考试信息...</div>
      </div>
    );
  }

  if (!examInfo) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Text>考试信息加载失败</Text>
      </div>
    );
  }

  if (!examStarted) {
    return (
      <div style={{ padding: '24px', maxWidth: '800px', margin: '0 auto' }}>
        <Card title="考试准备" style={{ textAlign: 'center' }}>
          <div style={{ marginBottom: 24 }}>
            <Title level={2}>{examInfo.title}</Title>
            <Tag color="blue" icon={<BookOutlined />}>
              {examInfo.course}
            </Tag>
          </div>

          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={8}>
              <Statistic title="考试时长" value={examInfo.duration} suffix="分钟" />
            </Col>
            <Col span={8}>
              <Statistic title="题目数量" value={examInfo.questions.length} suffix="题" />
            </Col>
            <Col span={8}>
              <Statistic title="总分" value={examInfo.totalScore} suffix="分" />
            </Col>
          </Row>

          <div style={{ marginBottom: 24 }}>
            <Title level={4}>考试说明</Title>
            <Paragraph>{examInfo.description}</Paragraph>
          </div>

          <div style={{ marginBottom: 24 }}>
            <Title level={4}>知识点</Title>
            <Space wrap>
              {examInfo.knowledgePoints.map((point, index) => (
                <Tag key={index} color="purple">{point}</Tag>
              ))}
            </Space>
          </div>

          <div style={{ marginBottom: 24 }}>
            <Title level={4}>考试规则</Title>
            <List
              size="small"
              dataSource={examInfo.rules}
              renderItem={(rule) => (
                <List.Item>
                  <Text>• {rule}</Text>
                </List.Item>
              )}
            />
          </div>

          <Button type="primary" size="large" onClick={startExam}>
            开始考试
          </Button>
        </Card>
      </div>
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      {/* 顶部信息栏 */}
      <Affix offsetTop={0}>
        <Card size="small" style={{ marginBottom: 16, backgroundColor: '#f0f2f5' }}>
          <Row gutter={16} align="middle">
            <Col span={8}>
              <Space>
                <FileTextOutlined />
                <Text strong>{examInfo.title}</Text>
              </Space>
            </Col>
            <Col span={4}>
              <Space>
                <ClockCircleOutlined />
                <Text type="danger" strong>{formatTime(timeLeft)}</Text>
              </Space>
            </Col>
            <Col span={4}>
              <Progress
                percent={getProgressPercent()}
                size="small"
                format={() => `${getAnsweredCount()}/${examInfo.questions.length}`}
              />
            </Col>
            <Col span={8} style={{ textAlign: 'right' }}>
              <Space>
                {autoSaving && <Text type="secondary">自动保存中...</Text>}
                {lastSaveTime && (
                  <Text type="secondary">
                    上次保存: {lastSaveTime.toLocaleTimeString()}
                  </Text>
                )}
                <Button
                  icon={<SaveOutlined />}
                  onClick={handleSaveAndExit}
                >
                  保存并退出
                </Button>
                <Button
                  type="primary"
                  icon={<SendOutlined />}
                  onClick={() => handleSubmit(false)}
                  loading={isSubmitting}
                >
                  提交考试
                </Button>
              </Space>
            </Col>
          </Row>
        </Card>
      </Affix>

      <Row gutter={16}>
        <Col span={18}>
          {/* 当前题目 */}
          {examInfo.questions[currentQuestion] && 
            renderQuestion(examInfo.questions[currentQuestion], currentQuestion)}

          {/* 题目导航 */}
          <div style={{ marginTop: 16 }}>
            <Space>
              <Button
                disabled={currentQuestion === 0}
                onClick={() => setCurrentQuestion(prev => prev - 1)}
              >
                上一题
              </Button>
              <Button
                disabled={currentQuestion === examInfo.questions.length - 1}
                onClick={() => setCurrentQuestion(prev => prev + 1)}
              >
                下一题
              </Button>
            </Space>
          </div>
        </Col>

        <Col span={6}>
          {renderQuestionNav()}
        </Col>
      </Row>
    </div>
  );
};

export default ExamTaking;
